﻿using FictionsDownload.BLL;
using FictionsDownload.Events;
using Zzw;
using FictionsDownload.Model;
using FictionsDownload.Static;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using static FictionsDownload.Static.FormEx;

namespace FictionsDownload.UI
{
    public partial class FormReadDirectory : Form
    {
        #region 内部变量
        private BookModel bookModel = new BookModel();
        private Book book = new Book();
        private Directory directory = new Directory();
        #endregion
        #region 公共属性和事件
        /// <summary>
        /// 选中章节
        /// </summary>
        public event EventHandler<SelectionDirectoryEventArgs> SelectionDirectory;
        #endregion
        #region 单例初始化
        private FormReadDirectory()
        {
            InitializeComponent();
            //
            this.TopLevel = false;
            this.FormBorderStyle = FormBorderStyle.None;
            this.Show();
            //
        }
        private static FormReadDirectory Instance;
        private static readonly object lockRoot = new object();
        /// <summary>
        /// 初始化实例
        /// </summary>
        public static FormReadDirectory GetIntance
        {
            get
            {
                if (Instance == null)
                {
                    lock (lockRoot)
                    {
                        if (Instance == null)
                        {
                            Instance = new FormReadDirectory();
                        }
                    }
                }
                return Instance;
            }
        }
        #endregion

        #region 控件初始化
        /// <summary>
        /// 窗口初始化之后，控件再做调整
        /// </summary>
        public void InitializeComponentCode()
        {
            dgv_directoryInit();
        }
        private void dgv_directoryInit()
        {
            this.dgv_directory.Location = new Point(0,0);
            //控件底部和容器贴合
            this.dgv_directory.Size = new Size(this.ClientSize.Width, this.ClientSize.Height);
            this.dgv_directory.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgv_directoryColumn(2);
        }
        private void dgv_directoryColumn(int column)
        {
            for (int i = 0; i < column; i++)
            {
                dgv_directory.Columns.Add(new DataGridViewColumn
                {
                    Name = i.ToString(),
                    HeaderText = i.ToString(),
                    CellTemplate = new DataGridViewTextBoxCell()
                });
            }
        }
        #endregion

        #region dgv_directory

        private void dgv_directory_Refresh()
        {
            var directories = directory.GetList<DirectoryModel>(d => d.BookId == bookModel.Id && d.State == true)
                .OrderBy(m=>m.SortIndex).ToDictionary(d=>d.Id,d=>d.Name);
            //清空数据
            if (dgv_directory.DataSource != null)
            {
                DataTable dt = (DataTable)dgv_directory.DataSource;
                dt.Rows.Clear();
                dgv_directory.DataSource = dt;
            }
            else
            {
                dgv_directory.Rows.Clear();
            }

            //添加数据
            DataGridViewRow row = new DataGridViewRow();
            for(int i = 0; i <= directories.Count; i++)
            {
                var item = directories.Skip(i).FirstOrDefault();
                if(item.Key != null)
                {
                    row.Cells.Add(new DataGridViewTextBoxCell { Value = item });
                    int columnIndex = (i + 1) % dgv_directory.Columns.Count;
                    if (columnIndex == 0)
                    {
                        dgv_directory.Rows.Add(row);
                        row = new DataGridViewRow();
                    }
                }
                else
                {
                    dgv_directory.Rows.Add(row);
                }
            }
        }
        #endregion

        /// <summary>
        /// 传入书籍ID显示章节列表
        /// </summary>
        /// <param name="bookId"></param>
        public void SetBook(string bookId)
        {
            bookModel = book.Get<BookModel>(b => b.Id == bookId);
            dgv_directory_Refresh();
        }

        private void dgv_directory_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.Value != null && e.Value.ToString().IsNoNullOrEmptyOrSpace())
            {
                e.Value = ((KeyValuePair<string, string>)e.Value).Value;
            }
        }

        private void dgv_directory_MouseClick(object sender, MouseEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            DataGridViewCell dataGridViewCell = GetClickedCell(dgv,e.X,e.Y);
            //没点到单元格  或  选择的行超过了总行数，返回
            if (dataGridViewCell == null || dataGridViewCell.Value == null)
            {
                dgv.ClearSelection();
                return;
            }
            else
            {
                string selectId = ((KeyValuePair<string, string>)dataGridViewCell.Value).Key;
                this.SelectionDirectory?.Invoke(this,new SelectionDirectoryEventArgs(selectId));
            }
        }
        /// <summary>
        /// 获取鼠标点击坐标的单元格
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="mouseX"></param>
        /// <param name="mouseY"></param>
        /// <returns></returns>
        private DataGridViewCell GetClickedCell(DataGridView dgv, int mouseX,int mouseY)
        {
            if (dgv.FirstDisplayedScrollingRowIndex < 0)
            {
                return null;
            }
            if (dgv.ColumnHeadersVisible == true && mouseY <= dgv.ColumnHeadersHeight)
            {
                return null;
            }
            int indexRow = dgv.FirstDisplayedScrollingRowIndex;
            int displayedRowCount = dgv.DisplayedRowCount(true);
            DataGridViewRow dataGridViewRow = null;
            for (int i = 1; i <= displayedRowCount;)
            {
                if (dgv.Rows[indexRow].Visible == true)
                {
                    Rectangle rect = dgv.GetRowDisplayRectangle(indexRow, true);
                    if (rect.Top <= mouseY && mouseY < rect.Bottom)
                    {
                        dataGridViewRow = dgv.Rows[indexRow];
                    }
                    i++;
                }
                indexRow++;
            }
            if (dataGridViewRow == null)
            {
                return null;
            }
            int indexColumn = dgv.FirstDisplayedScrollingColumnIndex;
            int displayedColumnCount = dgv.DisplayedColumnCount(true);
            for (int i = 1; i <= displayedColumnCount;)
            {
                if (dgv.Rows[indexColumn].Visible == true)
                {
                    Rectangle rect = dgv.GetColumnDisplayRectangle(indexColumn, true);
                    if (rect.Left <= mouseX && mouseX < rect.Right)
                    {
                        return dataGridViewRow.Cells[indexColumn];
                    }
                    i++;
                }
                indexColumn++;
            }
            return null;
        }
    }
}
